package com.example.seata.action;

import com.example.common.aware.MyApplicationContextAware;
import com.example.common.utils.Statistics;
import io.seata.rm.tcc.api.BusinessActionContext;
import io.seata.rm.tcc.api.TwoPhaseBusinessAction;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.JdbcOperations;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;

@Slf4j
@Component("tCCActionA")
public class TCCActionA implements TCCAction {

    @TwoPhaseBusinessAction(name = "my2Pc", commitMethod = "commit", rollbackMethod = "rollback")
    @Override
    public boolean prepare(BusinessActionContext actionContext, Object param) {
        Statistics.logInfo(log, "prepare", actionContext);
        try{
            JdbcOperations jdbcOperations
                    = new JdbcTemplate((DataSource) MyApplicationContextAware.getBean("dataSource1"));
            jdbcOperations.update("delete from my_entity where id = ?", param);
        }catch (Exception e){
            return true;
        }
//        throw new RuntimeException("prepare error");
        return true;
    }

    @Override
    public boolean commit(BusinessActionContext actionContext) {
        Statistics.logInfo(log, "commit", actionContext);
        try{
            JdbcOperations jdbcOperations = new JdbcTemplate((DataSource) MyApplicationContextAware.getBean("dataSource2"));
            jdbcOperations.update("delete from my_entity where id = ?");
        }catch(Exception e){
            return true;
        }
//        throw new RuntimeException("commit error");
        return true;
    }

    @Override
    public boolean rollback(BusinessActionContext actionContext) {
        Statistics.logInfo(log, "rollback", actionContext);
        return true;
    }
}
